<template>
  <view>
    <image :src="svgIcon" mode="aspectFill" style="width: 90rpx; height: 90rpx;" />
  </view>
</template>

<script>
	import Base64 from '@/components/base64.js';
export default {
  name: 'SvgIcon',
  props: {
    iconUrl: {
      type: String,
      required: true
    },
    svgStyle: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      svgIcon: ''
    }
  },
  methods: {
    async loadSvg(url) {
      try {
        wx.request({
          url: url,
          method: 'GET',
          responseType: 'text',
          success: (res) => {
            const svgText = res.data;
            const color = this.svgStyle.color || '#000000'; // 默认颜色为黑色
            const updatedSvg = this.changeColor(svgText, color);
            const base64Data = this.toBase64(updatedSvg);
            this.svgIcon = `data:image/svg+xml;base64,${base64Data}`;
          },
          fail: (error) => {
            console.error('Failed to load SVG:', error);
          }
        });
      } catch (error) {
        console.error('Failed to load SVG:', error);
      }
    },
    changeColor(sourceFile, color) {
      if (/fill="[^"]*"/.test(sourceFile)) {
        return sourceFile.replace(/fill="[^"]*"/g, `fill="${color}"`);
      } else {
        return sourceFile.replace(/<svg /g, `<svg fill="${color}" `);
      }
    },
    toBase64(str) {
      // 直接使用 Base64 编码库，如 `base64-js`
      return Base64.encode(str);
    }
  },
  watch: {
    iconUrl: {
      handler(newUrl) {
        this.loadSvg(newUrl);
      },
      deep: true,
      immediate: true
    }
  }
}
</script>